package org.judo.generate.mvc;

import java.util.ArrayList;
import java.util.StringTokenizer;

import org.judo.util.Util;

public class ParserUtil
{
	public static String getValue(String line,Context contextResult)
		throws ParseException
	{
		String split[] = line.split(":");
		
		if (split.length == 1)
			throw new ParseException("Need to specify a value after the ':' token");
		
		if (split[1].equals(""))
			throw new ParseException("Need to specify a value after the ':' token");
		
		String value = split[1].trim();
		
		ArrayList<String> paramerterizedNames = findContextVars(line);
		contextResult.addContextVars(paramerterizedNames);
		
		for (String param:paramerterizedNames)
		{
			if (!param.contains("|"))
				continue;
	
			String var = param.trim();
			String content = var.replace("$","").replace("{","").replace("}","");
			String parts[] = Util.split(content,'|');
			String newParam = "${"+parts[1]+"}";
			value = value.replace("${"+param+"}",newParam);
		}
		
		return value;
	}
	
	public static String getValue(String line)
		throws ParseException
	{
		String split[] = line.split(":");
		
		if (split.length == 1)
			throw new ParseException("Need to specify a value after the ':' token");
		
		if (split[1].equals(""))
			throw new ParseException("Need to specify a value after the ':' token");
		
		return split[1].trim();
	}

	public static String parseFreeText(String line,Context contextResult)
	{
		String result = "";
		
		ArrayList<String> paramerterizedNames = findContextVars(line); 
		
		contextResult.addContextVars(paramerterizedNames);
		result = line;
		
		for (String param:paramerterizedNames)
		{
			if (!param.contains("|"))
				continue;
	
			String var = param.trim();
			String content = var.replace("$","").replace("{","").replace("}","");
			String parts[] = Util.split(content,'|');
			String newParam = "${"+parts[1]+"}";
			result = result.replace("${"+param+"}",newParam);
		}
		
		return result;
	}
	
	protected static ArrayList<String> findContextVars(String str)
	{
		ArrayList<String> paramerterizedNames = new ArrayList<String>();
		char chars[] = str.toCharArray();
		
		boolean inParam = false;
		String curParamName = "";
		int symbolLocation = -1;
		
		for (int i=0;i<chars.length;i++)
		{
			if (inParam)
			{
				if (chars[i] == '}')
				{
					inParam = false;
					paramerterizedNames.add(curParamName);
	
					curParamName = "";
					continue;
				}
				
				curParamName += chars[i];
			}
			else
			{
				if (chars[i] == '$')
				{
					symbolLocation = i;
				}
				else if (chars[i] == '{')
				{
					if (i-1 == symbolLocation)
					{
						inParam = true;
						curParamName = "";
					}
				}
			}
		}
		
		return paramerterizedNames;
	}
}
